﻿using System.Text.RegularExpressions;

namespace RSuite.Common
{
    public static class StringUtil
    {
        public static string Combine(string seperator, params string[] parts)
        {
            for (var i = 0; i < parts.Length; i++)
            {
                if (i > 0)
                {
                    while (parts[i].StartsWith(seperator))
                    {
                        parts[i] = parts[i].Substring(seperator.Length);
                    }
                }
                if (i < parts.Length - 1)
                {
                    while (parts[i].EndsWith(seperator))
                    {
                        parts[i] = parts[i].Substring(0, parts[i].Length - seperator.Length);
                    }
                }
            }
            return string.Join(seperator, parts);
        }

        public static bool MatchFilePattern(string name, string pattern)
        {
            return MatchPattern(name, FilePatternToRegex(pattern), true);
        }

        private static bool MatchPattern(string name, string pattern, bool ignoreCase)
        {
            var options = ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None;

            return Regex.IsMatch(name, pattern, options);
        }

        private static string FilePatternToRegex(string pattern)
        {
            return string.Format("^{0}$", pattern.Replace(".", @"\.").Replace("*", ".*").Replace("?", "."));
        }
    }
}